package com.jstyle.jclifexd.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.HistoryHeartRangeAdapter;
import com.jstyle.jclifexd.adapter.PaceAdapter;
import com.jstyle.jclifexd.adapter.TrackRecordDetailAdapter;
import com.jstyle.jclifexd.daoManager.GpsDataDaoManager;
import com.jstyle.jclifexd.daoManager.HeartDataDaoManager;
import com.jstyle.jclifexd.daoManager.PathRecordDaoManager;
import com.jstyle.jclifexd.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.GpsData;
import com.jstyle.jclifexd.model.HeartData;
import com.jstyle.jclifexd.model.PaceData;
import com.jstyle.jclifexd.model.PathRecord;
import com.jstyle.jclifexd.model.StepDetailData;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.ChartDataUtil;
import com.jstyle.jclifexd.utils.CoordinateUtil;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.DouglasPeuckerGoogleUtil;
import com.jstyle.jclifexd.utils.HealthDataUtils;
import com.jstyle.jclifexd.utils.ResolveData;
import com.jstyle.jclifexd.utils.SchedulersTransformer;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.ShareGpsView;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;
import lecho.lib.hellocharts.view.PieChartView;

public class ExerciseHistoryGoogleActivity extends BaseActivity implements OnMapReadyCallback {


    @BindView(R.id.bt_trackhistory_mode)
    Button btTrackhistoryMode;
    @BindView(R.id.bt_trackhistory_diatance)
    Button btTrackhistoryDiatance;
    @BindView(R.id.recyclerView_track_detail)
    RecyclerView recyclerViewTrackDetail;
    @BindView(R.id.ColumnChartView_stephz)
    ColumnChartView ColumnChartView_stephz;
    @BindView(R.id.LineChartView_heart)
    LineChartView LineChartViewHeart;

    @BindArray(R.array.track_historydetail_array)
    String[] detailArray;
    @BindView(R.id.imageView6)
    ImageView imageView6;
    @BindView(R.id.iv_hr_levelHr_general)
    ImageView ivHrLevelHrGeneral;
    @BindView(R.id.iv_hr_levelHr_good)
    ImageView ivHrLevelHrGood;
    @BindView(R.id.iv_hr_levelHr_excellent)
    ImageView ivHrLevelHrExcellent;
    @BindView(R.id.iv_hr_levelHr_tooHigh)
    ImageView ivHrLevelHrTooHigh;
    @BindView(R.id.imageView7)
    ImageView imageView7;
    @BindView(R.id.bt_trackhistory_stephz)
    Button btTrackhistoryStephz;
    @BindView(R.id.bt_trackhistory_avghz)
    Button btTrackhistoryAvghz;
    @BindView(R.id.bt_speed)
    Button btSpeed;
    @BindView(R.id.bt_heart)
    Button btHeart;

    @BindView(R.id.bt_heart_range)
    Button btHeartRange;
    @BindView(R.id.bt_heart_report)
    Button btHeartReport;

    @BindView(R.id.bt_trackhistory_space)
    Button btTrackHistorySpace;
    @BindView(R.id.bt_pace_low)
    TextView btPaceLow;
    @BindView(R.id.bt_space_fast)
    TextView btSpaceFast;
    @BindView(R.id.iv_color)
    ImageView ivColor;
    @BindView(R.id.tv_pace_label)
    TextView tvPaceLabel;
    @BindView(R.id.RecyclerView_pace)
    RecyclerView RecyclerViewPace;
    @BindView(R.id.RecyclerView_heartRange)
    RecyclerView RecyclerViewHeartRange;
    @BindView(R.id.bt_trackhistory_avgHeart)
    Button btTrackhistoryAvgHeart;
    @BindView(R.id.button_title)
    Button buttonTitle;
    @BindArray(R.array.mode_name)
    String[] modeName;
    @BindString(R.string.heart_tips_0)
    String heartTips0;
    @BindString(R.string.heart_tips_1)
    String heartTips1;
    @BindString(R.string.heart_tips_2)
    String heartTips2;
    @BindString(R.string.heart_tips_3)
    String heartTips3;

    @BindView(R.id.tv_result)
    TextView tvResult;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.bt_no_heartdata)
    Button btNoHeartdata;
    private String endTime;
    private int startCount;
    private int endCount;
    private PathRecord pathRecord;
    @BindArray(R.array.color_heartReport_array)
    int[] heartReportColor;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AMAP_LOADED:
                    setupRecord();
                    break;
                default:
                    break;
            }
        }
    };
    private List<LatLng> mOriginLatLngList = new ArrayList<>();


    private TrackRecordDetailAdapter trackHistoryDetailAdapter;
    private int avgHeart;

    private ArrayList<Integer> stepList;
    private ArrayList<Integer> heartList;
    private ArrayList<LatLng> mShowList = new ArrayList<>();
    private SupportMapFragment mapFragment;
    FragmentManager fragmentManager;
    private boolean transformer;
    private String time;
    private String mPathDate;
    private String lowPaceString;
    private String fastPaceString;
    Boolean isshoewStep = false;
    Boolean isshoewHeart = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise_record_google);
        ButterKnife.bind(this);
        fragmentManager = getSupportFragmentManager();
        mapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
         mPathDate = getIntent().getStringExtra("DATE");
        transformer=getIntent().getBooleanExtra("isTransFormer",false);
        pathRecord = PathRecordDaoManager.getPathRecord(mPathDate);
        init();
    }

    private void init() {

        ScreenUtils.setTitleTypeface(buttonTitle);
        btTrackhistoryMode.setText(modeName[pathRecord.getExerciseMode() > 10 ? 10 : pathRecord.getExerciseMode()]);
        if (pathRecord == null) return;
        time = pathRecord.getMDate();
        buttonTitle.setText(DateUtil.getShowDay(ExerciseHistoryGoogleActivity.this, time));
        String duration = pathRecord.getMDuration();
        long startL = DateUtil.getGpsDateLong(time);
        long endL = startL + Integer.valueOf(duration) * 1000;
        endTime = DateUtil.getFormatTimeString(endL);
        startCount = DateUtil.get1MIndex(time, time.split(" ")[0] + " 00:00:00");
        endCount = DateUtil.get1MIndex(endTime, time.split(" ")[0] + " 00:00:00");
        initStepData();
        initHeartData();
        setRecyclerViewData();
      //  setPaceData();
        initGpsData();
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int i, int i1, int i2, int i3) {
                Rect scrollBounds = new Rect();
                ColumnChartView_stephz.getHitRect(scrollBounds);
                LineChartViewHeart.getHitRect(scrollBounds);

                if (!isshoewStep&&ColumnChartView_stephz.getLocalVisibleRect(scrollBounds)) {
                    isshoewStep = true;
                    ChartDataUtil.settingXAnimator(ColumnChartView_stephz, 0);
                }
                if (!isshoewHeart&&LineChartViewHeart.getLocalVisibleRect(scrollBounds)) {
                    isshoewHeart = true;
                    ChartDataUtil.settingXAnimator(LineChartViewHeart, 1);
                }

            }
        });
    }

    List<PaceData> paceList = new ArrayList<>();

    private void initGpsData() {
        isShowView(pathRecord.getExerciseMode());
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                 time = pathRecord.getMDate();
                int paceSize = 0;
                float maxDistance = Float.valueOf(pathRecord.getMDistance());
                int maxPaceSize = (int) (maxDistance / 1);
                float lastDistance = maxDistance % 1;
                boolean paceFinish=false;
                String startTime = time.split(" ")[0];
                String duration = pathRecord.getMDuration();
                long totalTime = Integer.valueOf(duration);
                long startL = DateUtil.getGpsDateLong(time);
                long endL = startL + Integer.valueOf(duration) * 1000;
                String endTime = DateUtil.getFormatTimeString(endL);
                List<GpsData> gpsDataList = GpsDataDaoManager.getPathRecord(time, endTime);
                int startCount = DateUtil.get1MIndex(time, time.split(" ")[0] + " 00:00:00");
                int endCount = DateUtil.get1MIndex(endTime, endTime.split(" ")[0] + " 00:00:00");
                float distance = 0;
                long distanceTime = 0;
                LatLng lastLng = null;
                long durationGps = 0;
                for (GpsData gpsData : gpsDataList) {
                    String date = gpsData.getDate();
                    int gpsCount = DateUtil.get1MIndex(date, time.split(" ")[0] + " 00:00:00");
                    if (gpsCount < startCount) continue;
                    if (gpsCount > endCount) {
                        PaceData paceData=new PaceData();
                        paceData.setPace(durationGps / distance);
                        paceData.setDistanceFinish(true);
                        paceList.add(paceData);
                        break;
                    }
                    if (distance == 0 || paceList.size() > paceSize) {
                        distanceTime = DateUtil.getGpsDateLong(date);
                        paceSize = paceList.size();
                    }
                    durationGps = DateUtil.getGpsDateLong(date) - distanceTime;

                    String[] LatitudeStringArray = gpsData.getLatitudeString().split(",");
                    String[] LongitudeStringArray = gpsData.getLongitudeString().split(",");
                    in:for (int i = 0; i < LatitudeStringArray.length; i++) {
                        LatLng latLng = CoordinateUtil.transformFromWGSToGCJGoogle(
                                Double.valueOf(LatitudeStringArray[i]), Double.valueOf(LongitudeStringArray[i]),transformer);
                        if (mOriginLatLngList.size() != 0) {
                            LatLng lastDistanceLng = mOriginLatLngList.get(mOriginLatLngList.size() - 1);
                            float[] results = new float[3];
                            Location.distanceBetween(lastDistanceLng.latitude, lastDistanceLng.longitude, latLng.latitude, latLng.longitude, results);
                            double betweenDis = results[0];
                           // Log.i(TAG, "subscribe: betweenDis "+betweenDis);
                            if (betweenDis > 5000) {
                                continue  in;
                            }
                        }
                        mOriginLatLngList.add(latLng);
                        if (lastLng != null) {
                            float[] results = new float[3];
                            Location.distanceBetween(lastLng.latitude, lastLng.longitude, latLng.latitude, latLng.longitude, results);
                            double betweenDis = results[0];
                            distance = (float) (distance + betweenDis);
                            if (paceList.size() == maxPaceSize) {
                                if (distance >= lastDistance * 1000) {
                                    long durtaion = 0;
                                    for (PaceData paceData : paceList) {
                                        durtaion += paceData.getPace();
                                    }
                                    PaceData paceData = new PaceData();
                                    paceData.setPace((totalTime - durtaion) / distance);
                                    paceData.setTime((totalTime - durtaion));
                                    paceData.setDistanceFinish(false);
                                    paceList.add(paceData);
                                    paceFinish=true;
                                }
                            }
                            if (distance >= 1000&&!paceFinish) {
                                long durtaion = DateUtil.getGpsDateLong(date) - distanceTime;
                                PaceData paceData=new PaceData();
                                paceData.setPace(durtaion / distance);
                                paceData.setDistanceFinish(true);
                                paceList.add(paceData);
                                distance = 0;
                            }
                        }
                        lastLng = latLng;
                    }
                    if (gpsDataList.indexOf(gpsData) == gpsDataList.size() - 1 && !paceFinish&& paceList.size() == paceSize) {
                        long durtaion = DateUtil.getGpsDateLong(date) - distanceTime;
                        PaceData paceData=new PaceData();
                        paceData.setPace(durtaion/1000);
                        paceData.setDistanceFinish(false);
                        paceList.add(paceData);
                    }
                }
                if (mOriginLatLngList.size() != 0)
                    mShowList.addAll(DouglasPeuckerGoogleUtil.DouglasPeucker(mOriginLatLngList, 1.35));
                Log.i(TAG, "subscribe: e" + mOriginLatLngList.size());
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                String time = pathRecord.getMDate();
                String startTime = time.split(" ")[0];
                setPaceData();
                isFinish = true;
                Message msg = handler.obtainMessage();
                msg.what = AMAP_LOADED;
                handler.sendMessage(msg);
                if (mShowList.size() == 0)
                    getSupportFragmentManager().beginTransaction().hide(mapFragment).commit();
                ;
            }
        });


    }

    private void initStepData() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                stepList = new ArrayList<>();
                List<StepDetailData> stepDetailDataList = StepDetailDataDaoManager.queryData(time.split(" ")[0] + " 00:00:00", endTime.split(" ")[0] + " 23:59:00");
                int stepLength = endCount > 1440 ? endCount : 1440;
                int[] stepArray = new int[stepLength];

                out:
                for (StepDetailData stepDetailData : stepDetailDataList) {
                    String date = stepDetailData.getDate();
                    String steps = stepDetailData.getMinterStep();
                    String[] stepString = steps.split(" ");//10分钟的步数
                    int stepCount = DateUtil.get1MIndex(date, time.split(" ")[0] + " 00:00:00");
                    in:
                    for (int i = 0; i < stepString.length; i++) {
                        int endStepCount = stepCount + i;
                        // Log.i(TAG, "subscribe: step "+endStepCount+" "+Integer.valueOf(stepString[i]));
                        if (endStepCount < startCount) continue in;
                        if (endStepCount >= endCount) continue out;
                        //  if(Integer.valueOf(stepString[i])!=0)
                        stepArray[endStepCount] = Integer.valueOf(stepString[i]);
                        //stepList.add(Integer.valueOf(stepString[i]));
                    }
                }
                for (int i = startCount; i < endCount; i++) {
                    stepList.add(stepArray[i]);
                }
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                initStepChartView(stepList);
            }
        });

    }

    private void initHeartData() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                List<HeartData> heartDataList = HeartDataDaoManager.queryGpsData(time, endTime);
                heartList = new ArrayList<>();
                for (HeartData hr : heartDataList) {
                    String date = hr.getTime();
                    int heartValue = hr.getHeart();
                    int hrCount = DateUtil.get1MIndex(date, time.split(" ")[0] + " 00:00:00");
                    if (hrCount < startCount) continue;
                    if (hrCount >= endCount) break;
                    heartList.add(heartValue);
                }

                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                initHeartChartView(heartList);
                String avgHeartString = getString(R.string.avg) + String.valueOf(avgHeart) + " BPM";
                btTrackhistoryAvgHeart.setText(getPaceSpannable(avgHeartString, String.valueOf(avgHeart)));
                trackHistoryDetailAdapter.setHeart(avgHeart);
                Log.i(TAG, "onComplete: heart");
            }
        });

    }


    private boolean isShowView(int mode) {
        boolean show = false;
        if (mode == ExerciseMode.Mode_RUN) {

        } else if (mode == ExerciseMode.Mode_CLIMB) {
            tvPaceLabel.setVisibility(View.GONE);
            btPaceLow.setVisibility(View.GONE);
            btSpaceFast.setVisibility(View.GONE);
            RecyclerViewPace.setVisibility(View.GONE);
        } else {
            ivColor.setVisibility(View.GONE);
            ColumnChartView_stephz.setVisibility(View.GONE);
            btTrackhistoryAvghz.setVisibility(View.GONE);
            btTrackhistoryStephz.setVisibility(View.GONE);
            tvPaceLabel.setVisibility(View.GONE);
            btPaceLow.setVisibility(View.GONE);
            btSpaceFast.setVisibility(View.GONE);
            RecyclerViewPace.setVisibility(View.GONE);
            btSpeed.setVisibility(View.GONE);
            btTrackHistorySpace.setVisibility(View.GONE);
        }
        return show;
    }

    private void setupRecord() {

        if (pathRecord != null && isFinish) {
            if (mShowList.size() == 0) return;
            LatLng startLatLng = mShowList.get(0);
            LatLng endLatLng = mShowList.get(mShowList.size() - 1);
            addOriginTrace(startLatLng, endLatLng, mShowList);
            if(!NetWorkUtil.isNetworkConnected(this))   showToast(getString(R.string.Network_not_availa_map));

        } else {
        }

    }

    boolean isFinish;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isshoewStep = false;
        isshoewHeart = false;
    }


    private void addOriginTrace(LatLng startPoint, LatLng endPoint,
                                List<LatLng> originList) {
        if (googleMap == null) return;
        googleMap.addPolyline(new PolylineOptions().color(
                Color.GREEN).addAll(originList));
        googleMap.addMarker(new MarkerOptions().position(
                startPoint).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.start)));
        googleMap.addMarker(new MarkerOptions().position(
                endPoint).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.end)));

        try {
            googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(),
                    80));
        } catch (Exception e) {
            e.printStackTrace();
        }

//        mOriginRoleMarker = mAMap.addMarker(new MarkerOptions().position(
//                startPoint).icon(
//                BitmapDescriptorFactory.fromBitmap(BitmapFactory
//                        .decodeResource(getResources(), R.drawable.walk))));
    }

    private void initHeartChartView(List<Integer> heartList) {

        float maxHeartRate = 0;
        List<PointValue> pointValues = new ArrayList<>();
        float totalHeartRate = 0;
        String account = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(account);
            UserInfoDaoManager.insertUser(userInfo);
        }
        String birthday = userInfo.getBirthday();
        int userYear = Integer.parseInt(birthday.split("-")[0]);
        Calendar calendar = Calendar.getInstance();
        int age = calendar.get(Calendar.YEAR) - userYear;
        int MHR = 220 - age;
        int[] heartRanges = new int[5];
        int count = 0;
        for (int i = 0; i < heartList.size(); i++) {
            float heartRate = heartList.get(i);
            int level = HealthDataUtils.getHeartRange(heartRate);
            if (level != -1) heartRanges[level]++;
            if (heartRate != 0) count++;
            totalHeartRate += heartRate;
            pointValues.add(new PointValue(i, heartRate));
            maxHeartRate = Math.max(maxHeartRate, heartRate);
        }
        getHeartReport(heartRanges, count);
        initHeartRange(heartRanges);
        avgHeart = count == 0 ? 0 : (int) (totalHeartRate / count);
        float top=0;
        if(maxHeartRate<120){
            top=130;
        }else if(maxHeartRate<150){
            top=160;
        }else if(maxHeartRate<180){
            top=190;
        }else{
            top=220;
        }
        ChartDataUtil.initDataChartView(LineChartViewHeart, -0.5f, top, heartList.size() - 0.7f, 0);
        LineChartViewHeart.setLineChartData(ChartDataUtil.getTrackHistoryHeartChart(this, pointValues));
    }

    private void getHeartReport(int[] heartRanges, int total) {
        float range0 = heartRanges[0];
        float range1 = heartRanges[1];
        float range2 = heartRanges[2];
        float range3 = heartRanges[3];
        float range4 = heartRanges[4];
        String tips = "";
        String level = "";
        int pieValue = -1;
        if (range4 > 5 || (range3 + range4) > 20 || range3 > 20) {//过高
            tips = heartTips3;
            ivHrLevelHrTooHigh.setVisibility(View.VISIBLE);
        } else if ((range2 >= 20 && range2 <= 30) || (range3 >= 10 && range3 <= 20) || (range4 > 0 && range4 <= 5 && range3 + range4 > 2) || range2 + range3 >= 20) {//优秀
            tips = heartTips2;
            ivHrLevelHrExcellent.setVisibility(View.VISIBLE);
        } else if ((range0 + range1 + range2 + range3 > 30 && range1 > 20) || (range3 > 0 && range3 < 10 && range2 + range3 > 2) || (range2 > 5 && range2 < 20) || range1 + range2 + range3 > 30) {//良好
            tips = heartTips1;
            ivHrLevelHrGood.setVisibility(View.VISIBLE);
        } else {//弱
            tips = heartTips0;
            if (total != 0) ivHrLevelHrGeneral.setVisibility(View.VISIBLE);
        }
        tvResult.setText(tips);
        if (total == 0) level = getString(R.string.No_data);



    }


    private int getHeartRange(float heartRate, int MHR) {
        int range = 0;
        if (heartRate >= 0.5f * MHR && heartRate <= 0.6f * MHR) {//热身
            range = 0;
        } else if (heartRate >= 0.6f * MHR && heartRate < 0.7f * MHR) {//燃脂
            range = 1;
        } else if (heartRate >= 0.7f * MHR && heartRate < 0.8f * MHR) {//有氧
            range = 2;
        } else if (heartRate >= 0.8f * MHR && heartRate < 0.9f * MHR) {//肌力
            range = 3;
        } else if (heartRate >= 0.9f * MHR) {//无氧
            range = 4;
        }
        return range;
    }

    private float getDistance(List<LatLng> list) {
        float distance = 0;
        if (list == null || list.size() == 0) {
            return 0;
        }
        for (int i = 0; i < list.size() - 1; i++) {
            LatLng firstLatLng = list.get(i);
            LatLng secondLatLng = list.get(i + 1);
            float[] results = new float[3];
            Location.distanceBetween(firstLatLng.latitude, firstLatLng.longitude,
                    secondLatLng.latitude, secondLatLng.longitude, results);
            double betweenDis = results[0];
            distance = (float) (distance + betweenDis);
        }
        return distance / 1000f;
    }

    private LatLngBounds getBounds() {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (mOriginLatLngList == null) {
            return b.build();
        }
        for (int i = 0; i < mOriginLatLngList.size(); i++) {
            b.include(mOriginLatLngList.get(i));
        }
        return b.build();

    }

    /**
     * 配速
     */
    private void setPaceData() {

        float minPace = 10000;
        float maxPace = 0;
        for (PaceData paceData : paceList) {
            if(paceData.isDistanceFinish()){
                minPace = Math.min(minPace, paceData.getPace());
                maxPace = Math.max(maxPace, paceData.getPace());
            }

        }
         lowPaceString = getString(R.string.Slowst) + DateUtil.getPaceTime((int) maxPace);
         fastPaceString = getString(R.string.Fast) + DateUtil.getPaceTime(minPace == 10000 ? 0 : (int) minPace);
        btPaceLow.setText(lowPaceString);
        btSpaceFast.setText(fastPaceString);
        PaceAdapter paceAdapter = new PaceAdapter(paceList, maxPace,minPace);
        RecyclerViewPace.setAdapter(paceAdapter);
        LinearLayoutManager linearLayoutManagerPace = new LinearLayoutManager(this);
        linearLayoutManagerPace.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewPace.setLayoutManager(linearLayoutManagerPace);
    }

    private void setRecyclerViewData() {
        trackHistoryDetailAdapter = new TrackRecordDetailAdapter(mOriginLatLngList, this, pathRecord, avgHeart);

        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        recyclerViewTrackDetail.setLayoutManager(flexboxLayoutManager);
        recyclerViewTrackDetail.setAdapter(trackHistoryDetailAdapter);

        float distance = Float.valueOf(pathRecord.getMDistance());//距离
        String showDistance = null;
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMinimumFractionDigits(2);
        numberFormat.setGroupingUsed(false);
        showDistance = ResolveData.getShowDistance(String.valueOf(distance));
        String showPace = ResolveData.getShowPace(this, pathRecord.getMAveragespeed());
        String distanceString = showDistance + ResolveData.getDistanceLabel();
        String avgPaceString = ResolveData.getDetailPaceLabel(this, showPace);

        btTrackhistoryDiatance.setText(getPaceSpannable(distanceString, showDistance));
        btTrackHistorySpace.setText(getPaceSpannable(avgPaceString, showPace));

    }

    private static final String TAG = "ExerciseHistoryActivity";

    private void initHeartRange(int[] heartRanges) {
        int total = 0;
        for (int i = 0; i < 5; i++) {
            total += heartRanges[i];
        }
        HistoryHeartRangeAdapter historyHeartRangeAdapter = new HistoryHeartRangeAdapter(this, heartRanges, total);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewHeartRange.setAdapter(historyHeartRangeAdapter);
        RecyclerViewHeartRange.setLayoutManager(linearLayoutManager);
    }

    private void initStepChartView(List<Integer> stepList) {

        int time = Integer.valueOf(pathRecord.getMDuration());
        float step = TextUtils.isEmpty(pathRecord.getMStep()) ? 0 : Float.valueOf(pathRecord.getMStep());
        int stepM = (int) (step * 60 / time);
        String paceStringAvg = getString(R.string.avg) + stepM + "steps/m";
        btTrackhistoryAvghz.setText(getPaceSpannable(paceStringAvg, stepM + ""));
        if (stepM == 0) return;
        float max = 0;
        for (Integer data : stepList) {
            max = Math.max(data, max);
        }

        if(stepList.size()>5){
            ChartDataUtil.initDataChartView(ColumnChartView_stephz, -0.5f, max == 0 ? 2 : max * 1.2f, time / 60 + 0.5f, 0);
        }else{
            ChartDataUtil.initDataChartView(ColumnChartView_stephz, -0.5f, max == 0 ? 2 : max * 1.2f,20-stepList.size(), 0);
        }
        ColumnChartView_stephz.setColumnChartData(ChartDataUtil.getTrackStepColumnChart(this, time, stepList));

        if (mShowList.size() == 0){
            if (!isshoewStep) {
                isshoewStep = true;
                ChartDataUtil.settingXAnimator(ColumnChartView_stephz, 0);
            }
        }


    }

    private float max = 0;

    private List<Float> string2List(String data) {
        List<Float> list = new ArrayList<>();
        if (TextUtils.isEmpty(data)) return list;
        String[] datas = data.split(",");
        for (String value : datas) {
            list.add(Float.valueOf(value));
        }

        return list;
    }

    @OnClick({R.id.imageView6, R.id.imageView7})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.imageView6:
                finish();
                break;
            case R.id.imageView7:
                ShareGpsView shareGpsView=new ShareGpsView(this,DateUtil.getShowDayTrack(this, time));
                final Bitmap bitmapGps=shareGpsView.getBitmap();
                if(null!=googleMap)
                this.googleMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
                    @Override
                    public void onSnapshotReady(Bitmap bitmap) {
                        ScreenUtils.shareMapFile(ExerciseHistoryGoogleActivity.this,bitmap,bitmapGps, scrollView,mPathDate,fastPaceString,lowPaceString);
                    }
                });

                break;
        }
    }

    private Spannable getDistanceSpannable(String text, String startText) {
        int start = text.indexOf(startText);
        int end = start + startText.length();
        Spannable kcalSpannable = new SpannableString(text);
        setSizeSpannable(kcalSpannable, start, end, 10);
        return kcalSpannable;
    }

    private Spannable getPaceSpannable(String text, String startText) {
        int start = text.indexOf(startText);
        int end = start + startText.length();
        Spannable kcalSpannable = new SpannableString(text);
        setSizeSpannable(kcalSpannable, start, end, 20);
        return kcalSpannable;
    }

    private void setSizeSpannable(Spannable word, int start, int end, int textSize) {
        word.setSpan(new AbsoluteSizeSpan(textSize, true), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }

    private final static int AMAP_LOADED = 2;


    @OnClick(R.id.bt_heart_range)
    public void onViewClicked() {
        startActivity(HeartTipsActivity.class, HeartTipsActivity.TipsType, HeartTipsActivity.TipsType_ActivityHeart);

    }

    GoogleMap googleMap;

    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap = googleMap;
        UiSettings mUiSettings = googleMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setCompassEnabled(false);
        mUiSettings.setMyLocationButtonEnabled(false);
        mUiSettings.setScrollGesturesEnabled(false);
        mUiSettings.setZoomGesturesEnabled(false);
        googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if(Utils.isFastClick()){return;}
                Intent intent = new Intent(ExerciseHistoryGoogleActivity.this, TrackHistoryGoogleActivity.class);
                intent.putExtra("track", mShowList);
                startActivity(intent);
            }
        });
        Message msg = handler.obtainMessage();
        msg.what = AMAP_LOADED;
        handler.sendMessage(msg);
    }
}
